package com.ck.jdk8.foreach;



import org.junit.Test;

import java.time.Duration;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Classname ForEachEample
 * @Description 参照 https://blog.csdn.net/TimHeath/article/details/71275179
 * @Date 2021/7/5 16:40
 * @Created by lpc
 */
public class ForEachEample {

    /**
     * 遍历大于5的集合
     */
    @Test
    public void  Test(){
        List<Integer> list = Arrays.asList(2,3,5,4,1,8,10,12);
        //传统写法
        for (Integer in: list) {
            if (in > 5){
                System.out.println(in);
            }
        }

        //stream写法
        list.stream().filter((i) -> i>5).forEach(System.out::println);
    }

    /**
     * 无限流 数字总是等差递增，差值为1
     */
    @Test
    public void Test2(){
        Stream.iterate(1,(x)->x+1).forEach(System.out::println);
    }

    /**
     * 大于等于0小于1的随机数
     */
    @Test
    public void test2() {
        Stream.generate(() -> Math.random()).forEach(System.out::println);
    }

    /**
     * 将集合中的每一个元素+1，并转为字符串
     */
    @Test
    public void Test3() {
        List<Integer> list = Arrays.asList(1,2,3,4,5);
        List<String> result = list.stream()
                .map(x -> String.valueOf(++x))
                .collect(Collectors.toList() );
        System.out.println(result);
    }

    /**
     * 串行流和并行流差别就是单线程和多线程的执行
     * 参照 https://blog.csdn.net/TimHeath/article/details/71366448
     */
    @Test
    public void Test4() {
        // 开始时间
        LocalTime start = LocalTime.now();
        List<Integer> list = new ArrayList<>();
        for (int i = 10000 ; i>=1 ; i--){
            list.add(i);
        }
        list.stream()//获取串行流
                .sorted()//按从大到小顺序排序
                .count();//count()是终止操作，有终止操作才会执行中间操作sorted()
        // 终止时间
        LocalTime end = LocalTime.now();
        // 时间间隔
        Duration duration = Duration.between(start,end);
        // 输出时间间隔毫秒值
        System.out.println(duration.toMillis());
    }


    @Test
    public void Test5() {
        LocalTime start = LocalTime.now();
        List<Integer> list = new ArrayList<>();
        for (int i = 10000 ; i>=1 ; i--){
            list.add(i);
        }
        list.parallelStream()//获取并行流
                .sorted()
                .count();

        LocalTime end = LocalTime.now();
        Duration duration = Duration.between(start,end);
        System.out.println(duration.toMillis());
    }
}
